<template>
  <div>
    <el-dialog
      title="数据列配置"
      :visible.sync="colsShowing"
      width="640px"
      top="50px"
      v-dialogDrag
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-table
        stripe
        border
        ref="multipleTable"
        :data="colsData"
        v-loading="colsLoading"
        element-loading-text="数据加载中..."
        :cell-style="{ padding: '1px' }"
        height="380px"
        style="width: 100%"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center"
          fixed="left"
        />
        <el-table-column
          prop="label"
          label="数据列名"
          align="center"
          header-align="center"
          min-width="150"
        />
        <el-table-column
          prop="width"
          label="显示宽度"
          align="center"
          header-align="center"
          min-width="80"
        />
        <el-table-column
          prop="precision"
          label="保留小数"
          align="center"
          header-align="center"
          min-width="80"
        />
        <el-table-column
          label="操作"
          width="150"
          align="center"
          header-align="center"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              circle
              icon="el-icon-edit"
              @click="edit(scope.$index)"
            />
            <el-button
              size="mini"
              circle
              icon="el-icon-arrow-up"
              :disabled="scope.$index === 0"
              @click="moveUp(scope.$index)"
            />
            <el-button
              size="mini"
              circle
              icon="el-icon-arrow-down"
              :disabled="scope.$index === colsData.length - 1"
              @click="moveDown(scope.$index)"
            />
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="init"
          type="info"
          :v-loading="colsShowing"
          size="mini"
          >恢复默认</el-button
        >
        <el-button
          @click="save"
          type="primary"
          :v-loading="colsShowing"
          size="mini"
          >保 存</el-button
        >
        <el-button @click="colsShowing = false" size="mini">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="列配置"
      :visible.sync="rowEditing"
      width="350px"
      :close-on-click-modal="false"
    >
      <div style="height: 30px; width: 100%" align="center">
        <h3>{{ e_label }}</h3>
      </div>
      <el-row style="height: 50px">
        <span>显示宽度：</span>
        <el-input-number
          v-model="e_width"
          :min="120"
          :max="500"
          :step="10"
          :precision="0"
          size="medium"
          controls-position="right"
        ></el-input-number>
        <span> px</span>
      </el-row>
      <template v-if="precShowing">
        <el-row style="height: 50px">
          <span>保留小数：</span>
          <el-input-number
            v-model="e_precision"
            :min="0"
            :max="10"
            :step="1"
            :precision="0"
            size="medium"
            controls-position="right"
          ></el-input-number>
          <span> 位</span>
        </el-row>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSave" size="mini"
          >确 定</el-button
        >
        <el-button @click="rowEditing = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
  <!-- 引用页面 demo -->
  <!--
  <ccc ref="ccc"></ccc>
  <el-button class="search-btn" type="" icon="el-icon-setting" @click="cccEvent('show', cccTable)">配置列</el-button>
  <el-table :key='tableKey' :data="listData" :v-loading="listLoading" border fit highlight-current-row>
      <template v-for="col in cccData">
        <el-table-column :key="col.id" :prop="col.prop" :label="col.label"
          :width="col.width" :min-width="col.minWidth" :class-name="col.className"
          :align="col.align" :header-align="col.headerAlign"
          :sortable="col.sortable" :formatter="col.formatter">
        </el-table-column>
      </template>

      <el-table-column align="center" header-align="center" label="操作" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  -->
</template>

<script>
import { Loading } from "element-ui";
import { getUserInfo } from "../utils/utilInfo";
import {excelDefColumnUser, excelMoreDefColumnUser, loadDefColumnUser, saveDefColumnUser} from "../api/tools/columnInfo";
// import ccc from '@/views/admin/ccc'

// 自定义列配置，弹框页面
export default {
  name: "custom-column-config",
  // components: { ccc },
  data() {
    return {
      /*
      cccData: [],
      cccTable: 'dm_dwbm',
      */
      colsTable: "",
      colsType: "",
      colsData: [],
      colsLoading: false,
      colsShowing: false,
      colsUser: getUserInfo.userName,
      /* 网关服务名 + 路由 */
      urlHeader: process.env.BASE_API,
      rowEditing: false,
      precShowing: true,
      e_index: null,
      e_label: null,
      e_width: null,
      e_precision: null,
      json: []
    };
  },
  beforeUpdate() {
    this.$nextTick(() => {
      this.$refs.multipleTable.doLayout();
    });
  },
  methods: {
    // 引用页面需要定义
    /**
     cccEvent(method, table) {
      if (method === 'show') {
        this.$refs.ccc.show(table)
      } else if (method === 'load') {
        new Promise((resolve, reject) => {
          resolve(this.$refs.ccc.load(table))
        }).then(response => {
          this.cccData = response
        })
      } else if (method === 'export') {
        let vo = { tableCode: table, param: this.listQuery, url: '/dm/dwbm/page', method: 'GET', fileName: '单位编码' }
        this.$refs.ccc.exportExcel(vo)
      }
    },
     */

    async load(tableCode) {
      const that = this
      const param = {
        tableCode: tableCode,
        username: this.colsUser,
        visiable: "1",
      };
      let cols = [];
      await loadDefColumnUser(param).then((response) => {
        if (response.code == 0) {
          cols = response.data
          cols.forEach((item, index) => {
            if (
              item.formatter !== undefined &&
              item.formatter !== null &&
              item.formatter !== ""
            ) {
              item.formatter = new Function(
                "row, column, value, index",
                item.formatter
              );
            }
          });
        }
      });
      return cols;
    },
    async show(tableCode, tableType) {
      this.colsTable = tableCode;
      this.colsType = tableType;
      this.colsShowing = true;
      this.colsLoading = true;
      this.colsData = [];
      const cols = [];
      const param = { tableCode: this.colsTable, username: this.colsUser };
      await loadDefColumnUser(param).then((response) => {
        response.data.forEach((item, index) => {
          if (item.formatType == 'DECIMAL' && item.formatValue) {
            cols.push({
              prop: item.field,
              label: item.title,
              width: item.minWidth,
              enable: item.visiable,
              precision: item.formatValue
            });
          } else {
            cols.push({
              prop: item.field,
              label: item.title,
              width: item.minWidth,
              enable: item.visiable,
              precision: '-'
            });
          }
        });
        this.colsData = cols;
        this.colsLoading = false;
      });
      const selections = [];
      this.colsData.forEach((item, index) => {
        if (item.enable == "1") {
          selections.push(this.colsData[index]);
        }
      });
      // 初始化启用状态
      selections.forEach((row) => {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      });
    },
    save: function () {
      // 获取要显示的列
      const selection = this.$refs.multipleTable.selection;
      if (selection.length == 0) {
        this.$message("请至少选择一列");
        return false;
      }
      // 开启进度条
      const loadingInstance = Loading.service({
        fullscreen: true,
        text: "正在保存...",
      });
      const showProps = [];
      selection.forEach((item) => {
        showProps.push(item.prop);
      });
      // 获取所有列
      const rows = this.$refs.multipleTable.data;
      const attrs = {};
      rows.forEach((item, index) => {
        const attr = {
          index: index,
          width: item.width,
          precision: item.precision,
        };
        if (showProps.indexOf(item.prop) > -1) {
          attr.enable = "1";
        } else {
          attr.enable = "0";
        }
        attrs[item.prop] = attr;
      });
      // 组装参数对象
      const vo = {};
      vo.username = this.colsUser;
      vo.tableCode = this.colsTable;
      vo.colsAttr = attrs;
      // 提交保存
      saveDefColumnUser(vo).then((response) => {
        // 关闭进度条
        loadingInstance.close();
        if (response.code === 0) {
          this.$message({ message: "保存成功！", type: "success" });
          this.$parent.cccEvent("load", this.colsTable, this.colsType);
          this.colsShowing = false;
        } else {
          this.$message.error("保存失败！");
        }
      });
    },
    async init() {
      this.colsData = [];
      const cols = [];
      const param = { tableCode: this.colsTable };
      await loadDefColumnUser(param).then((response) => {
        response.data.forEach((item, index) => {
          if (item.formatType == 'DECIMAL' && item.formatValue) {
            cols.push({
              prop: item.field,
              label: item.title,
              width: item.minWidth,
              enable: item.visiable,
              precision: item.formatValue
            });
          } else {
            cols.push({
              prop: item.field,
              label: item.title,
              width: item.minWidth,
              enable: item.visiable,
              precision: '-'
            });
          }
        });
        this.colsData = cols;
      });
      const selections = [];
      this.colsData.forEach((item, index) => {
        if (item.enable == "1") {
          selections.push(this.colsData[index]);
        }
      });
      // 初始化启用状态
      selections.forEach((row) => {
        this.$refs.multipleTable.toggleRowSelection(row, true);
      });
    },
    moveUp(index, row) {
      const that = this;
      // console.log('上移', index, row)
      // console.log(that.colsData[index])
      if (index > 0) {
        const upData = that.colsData[index - 1];
        that.colsData.splice(index - 1, 1);
        that.colsData.splice(index, 0, upData);
      } else {
        alert("已经是第一条，不可上移");
      }
    },
    moveDown(index, row) {
      const that = this;
      // console.log('下移', index, row)
      if (index + 1 === that.colsData.length) {
        alert("已经是最后一条，不可下移");
      } else {
        // console.log(index)
        const downData = that.colsData[index + 1];
        that.colsData.splice(index + 1, 1);
        that.colsData.splice(index, 0, downData);
      }
    },
    edit(index) {
      this.rowEditing = true;
      this.e_index = index;
      const row = this.colsData[index];
      if (row.precision === "-") {
        this.precShowing = false;
      } else {
        this.precShowing = true;
      }
      this.e_label = row.label;
      this.e_width = row.width;
      this.e_precision = row.precision;
    },
    editSave() {
      const index = this.e_index;
      this.colsData[index].width = this.e_width;
      this.colsData[index].precision = this.e_precision;
      this.rowEditing = false;
    },
    async exportExcel(obj) {
      // 开启进度条
      const loadingInstance = Loading.service({
        fullscreen: true,
        text: "正在导出...",
      });
      var fileName = obj.fileName;
      const vo = {};
      vo.username = this.colsUser;
      vo.tableCode = obj.tableCode;
      vo.fileName = fileName;
      vo.httpUrl = this.urlHeader + obj.url;
      vo.httpMethod = obj.method;
      vo.httpParam = obj.param;
      let total = obj.total;
      console.log('total', total)
      if (total && total > 2000) {
        try {
          const res = await excelMoreDefColumnUser(vo);
          this.$message({
            message: res.message,
            type: 'success'
          });
          loadingInstance.close();
        } catch (error) {
          loadingInstance.close();
        }
      } else {
        try {
          const res = await excelDefColumnUser(vo);
          console.log("导出", res);
          if (res) {
            // 关闭进度条
            loadingInstance.close();
            var blob = new Blob([res], {
              type: "application/vnd.ms-excel",
            });
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName);
            } else {
              var link = document.createElement("a");
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              window.URL.revokeObjectURL(link.href);
            }
          }
        } catch (error) {
          loadingInstance.close();
        }
      }
    },
  },
};
</script>

<style scoped>
</style>
